const  mongoose  = require('mongoose');
const jwt = require('jsonwebtoken');
const { studentsModel} = require('./../models/studentsModel');
async function useuser(req,res) {
    //添加数据到数组中
    let result = await mongoose.model(studentsModel).find({ ...req.body });
    console.log(result)
   //向浏览器返回数据
   if(result.length>0){
         // 生成 token
    const token = jwt.sign(
        { user: result[0] }, //  用户信息
        'user',  // 密钥，任意字符串
        { expiresIn: 1000000 } 
    );
       res.send({
           message: "登录成功",
           code: 200,
           token:"Bearer " + token,
           user:result
        //    user:{phone:result[0].phone,password:result[0].password}
       });

   }else{
    res.send({
        message: "登录失败",
        code: 200,
    });
   }
}
async function  useuserRegist(req,res){
     //添加数据到数组中
     console.log({ ...req.body })
     let result = await mongoose.model(studentsModel).find({ phone:req.body.phone });
     console.log(result)
     if(result.length>0){
        res.send({
            message: 0,
            //用户已注册
            code: 200,
        });
     }
     else{
         await mongoose.model(studentsModel).create({ ...req.body });
        //向浏览器返回数据
        res.send({
            //注册成功
            message: 1,
            status: "ok",
        });
     }
}
//修改学生数据
async function updatstudent(req,res) {
    console.log(req.body)
    // let result = await mongoose.model("studentsModel").updateOne({phone:req.body.phone},{name:req.body.name,gender:req.body.gender,avatar:req.body.avatar});
    let result = await mongoose.model("studentsModel").updateOne({phone:req.body.phone},{...req.body});
    //向浏览器返回数据
    res.send({
        message: "修改成功",
        status: "ok",
        student:result
    });
}
module.exports = {
    useuser,useuserRegist, updatstudent
}